package com.rc.saas.tenant.service.car;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.mapper.car.TenantCarNumberMapper;
import com.rc.saas.tenant.search.car.CarNumberSearch;
import com.rc.saas.tenant.vo.car.TenantCarNumberVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Sven on 2021/06/21
 */
@Service
public class TenantCarNumberServiceImpl implements TenantCarNumberService {

    /*车牌号验证*/
    private final String carNumRegex = "^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[a-zA-Z](([DFAB]((?![IO])[a-zA-Z0-9](?![IO]))[0-9]{4})|([0-9]{5}[DFAB]))" +
            "|[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1})$";

    @Autowired
    private TenantCarNumberMapper tenantCarNumberMapper;

    @Override
    public TenantCarNumberMapper getMapper() {
        return tenantCarNumberMapper;
    }

    @Override
    public PageInfo<TenantCarNumberVo> listPageByTenant(CarNumberSearch search) {
        TenantCarNumberVo distinceIds = tenantCarNumberMapper.selectByDistinctIds();
        if (distinceIds!=null){
            search.setIds(StringUtils.isNotBlank(distinceIds.getIds())? Arrays.asList(distinceIds.getIds().split(","))
                    :new ArrayList<String>());
        }
        PageHelper.startPage(search.getOffset(), search.getLimit());
        //完整车牌号
        String fullCarNum = search.getCarNum();

        if (fullCarNum != null && fullCarNum.length() > 2 && fullCarNum.matches(carNumRegex)) {
            String carArea = fullCarNum.substring(0, 1);
            String carLetter = fullCarNum.substring(1, 2);
            String carNum = fullCarNum.substring(2);
            search.setCarArea(carArea);
            search.setCarLetter(carLetter);
            search.setCarNum(carNum);
        }
        List<TenantCarNumberVo> list = tenantCarNumberMapper.listByTenant(search);
        return new PageInfo<>(list);
    }

    @Override
    public TenantCarNumberVo selectById(Long numberId) {
        return tenantCarNumberMapper.selectById(numberId);
    }
}
